package com.prs.crm.action.crm.report;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jfree.data.general.AbstractDataset;

import com.prs.crm.action.ReportAction;
import com.prs.crm.context.Constrains;
import com.prs.crm.domain.crm.Liaison;
import com.prs.crm.domain.crm.Linkman;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.report.ChartResult;
import com.prs.crm.report.ChartService;
import com.prs.crm.report.ExportConfig;
import com.prs.crm.report.ReportCell;
import com.prs.crm.report.ReportTable;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.crm.CustomerService;
import com.prs.crm.service.crm.LinkmanService;

public class CustomerAnalysisAction extends ReportAction {
	private static final long serialVersionUID = -475969990585096888L;

	private Linkman linkman;
	private LinkmanService linkmanService;
	private CustomerService customerService;
	private ChartService chartService;
	private ChartResult chartResult;
	private PaginationSupport pagination;

	private Date datestart;
	private Date dateend;
	private int exportType;
	private Integer state;
	private String year;
	private String month;
	private Person person;
	private String leaveName;
	private String merit;
	private String ids;
	private String category;
	private Date beginTime;
	private Date endTime;

	@Action("customerCount")
	public String customerCount() {
		return SUCCESS;
	}

	@Action("contactCount")
	public String contactCount() {
		return SUCCESS;
	}

	@Action("customerBusiness")
	public String customerBusiness() {
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	@Action(value = "viewCustomerPie", results = {
			@Result(name = "success", type = "chain", location = "customerCount"),
			@Result(name = "error", type = "chain", location = "customerCount") })
	public String viewCustomerPie() {
		if (datestart == null || dateend == null) {
			addActionError("开始或者结束时间不能为空");
			return ERROR;
		}
		Collection<Object[]> dataList = (Collection<Object[]>) this
				.getCustomerService().getCustomerTypeReport(datestart, dateend);
		chartResult = chartService.export(chartService.fillDataset(dataList,
				Constrains.REPORT_PIECHART), "客户类型统计", "customerInfo");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	@Action(value = "viewCustomerBusinessBarchar", results = {
			@Result(name = "success", type = "chain", location = "customerBusiness"),
			@Result(name = "error", type = "chain", location = "customerBusiness") })
	public String viewCustomerBusinessBarchar() {
		if (datestart == null || dateend == null) {
			addActionError("开始或者结束时间不能为空");
			return ERROR;
		}
		Collection<Object[]> dataList = (Collection<Object[]>) this
				.getCustomerService().getCustomerBusinessReport(datestart,
						dateend);
		chartResult = chartService
				.export(chartService.fillDataset(dataList,
						Constrains.REPORT_BARCHART), "客户行业统计", "数量", "",
						"customerInfo");
		return SUCCESS;
	}

	@Action(value = "viewContactCountLine", results = { @Result(name = "success", type = "chain", location = "contactCount") ,
			@Result(name = "error", type = "chain", location = "contactCount") })
			public String viewContactCountLine() {
				Date dates = null;
				try {
					if (this.getState() == 1) {
						dates = SimpleDateFormat.getDateInstance().parse(
								this.getYear() + "-01-01");
					} else {
						dates = SimpleDateFormat.getDateInstance().parse(
								this.getYear() + "-" + this.getMonth() + "-01");
					}
				} catch (ParseException e) {
					// e.printStackTrace();
				}
				if (merit == null) {
					addActionError("客户价值不能为空");
					return ERROR;
				}
				if (leaveName == null || leaveName.trim().equals("")) {
					addActionError("分配人不能为空");
					return ERROR;
				}
		AbstractDataset dataSet = chartService.fillLineChartSouce(this
				.getCustomerService().getReportSouce(dates, person, state,
						merit), state, Constrains.REPORT_BARCHART, year, month);
		chartResult = chartService.exportLineChart(dataSet, "客户联络统计", "次数", "",
				"customerInfo");
		return SUCCESS;
	}

	@Action(value = "viewContactCountPie", results = {
			@Result(name = "success", type = "chain", location = "contactCount"),
			@Result(name = "error", type = "chain", location = "contactCount") })
	public String viewContactCountPie() {
		Date dates = null;
		try {
			if (this.getState() == 1) {
				dates = SimpleDateFormat.getDateInstance().parse(
						this.getYear() + "-01-01");
			} else {
				dates = SimpleDateFormat.getDateInstance().parse(
						this.getYear() + "-" + this.getMonth() + "-01");
			}
		} catch (ParseException e) {
			// e.printStackTrace();
		}
		if (merit == null) {
			addActionError("客户价值不能为空");
			return ERROR;
		}
		if (leaveName == null || leaveName.trim().equals("")) {
			addActionError("分配人不能为空");
			return ERROR;
		}
		Collection<?> dataList = this.getCustomerService().getReportSouce(
				dates, person, state, merit);
		chartResult = chartService.export(chartService.fillLineChartSouce(
				dataList, state, Constrains.REPORT_PIECHART, year, month),
				"客户跟进走势", "customerInfo");
		return SUCCESS;
	}

	@Action(value = "viewContactCountBar", results = { @Result(name = "success", type = "chain", location = "contactCount") ,
			@Result(name = "error", type = "chain", location = "contactCount") })
			public String viewContactCountBar() {
				Date dates = null;
				try {
					if (this.getState() == 1) {
						dates = SimpleDateFormat.getDateInstance().parse(
								this.getYear() + "-01-01");
					} else {
						dates = SimpleDateFormat.getDateInstance().parse(
								this.getYear() + "-" + this.getMonth() + "-01");
					}
				} catch (ParseException e) {
					// e.printStackTrace();
				}
				if (merit == null) {
					addActionError("客户价值不能为空");
					return ERROR;
				}
				if (leaveName == null || leaveName.trim().equals("")) {
					addActionError("分配人不能为空");
					return ERROR;
				}
		Collection<?> dataList = this.getCustomerService().getReportSouce(
				dates, person, state, merit);
		chartResult = chartService.export(chartService.fillLineChartSouce(
				dataList, state, Constrains.REPORT_BARCHART, year, month),
				"客户跟进走势", "次数", "", "customerInfo");
		return SUCCESS;
	}

	@Action("customerInfo")
	public String customerInfo() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Liaison.class);
		category = ReportUtils.URLDecode(this.getCategory());
		Date dates = null;
		if (category != null && category.indexOf("周") != -1
				&& this.getState() == 2) {
			String week = category.substring(0, category.indexOf("周"));
			int day = Integer.parseInt(week) * 7;
			int monthDay = ReportUtils.getDaysByMonth(Integer.parseInt(this
					.getYear()), Integer.parseInt(this.getMonth()));
			if (day > monthDay) {
				int temp = monthDay - (7 - (day - monthDay));
				dates = ReportUtils.convertToDate(this.getYear(), this
						.getMonth(), temp + "");
				if (dates != null) {
					criteria.add(Restrictions.ge("liaisonTime", dates));
					beginTime = dates;
					endTime = ReportUtils.convertToDate(this.getYear(), ""
							+ (Integer.parseInt(this.getMonth()) + 1));
					criteria.add(Restrictions.lt("liaisonTime", endTime));
				}
			} else {
				endTime = ReportUtils.convertToDate(Integer.parseInt(year),
						Integer.parseInt(month), day, 23, 59, 59);
				int bengin = day - 7 == 0 ? 1 : day - 7;
				beginTime = ReportUtils.convertToDate(this.getYear(), this
						.getMonth(), bengin + "");
				if (beginTime != null)
					criteria.add(Restrictions.ge("liaisonTime", beginTime));
				if (endTime != null)
					criteria.add(Restrictions.le("liaisonTime", endTime));
			}
		} else if (category != null && category.indexOf("月") != -1
				&& this.getState() == 1) {
			String mon = category.substring(0, category.indexOf("月"));
			dates = ReportUtils.convertToDate(this.getYear(), mon);
			if (dates != null) {
				criteria.add(Restrictions.ge("liaisonTime", dates));
				beginTime = dates;
				Calendar c = Calendar.getInstance();
				c.setTime(dates);
				c.add(Calendar.MONTH, 1);
				endTime = c.getTime();
				criteria.add(Restrictions.lt("liaisonTime", endTime));
			}
		}

		if (merit != null && merit.trim().length() > 0) {
			merit = ReportUtils.URLDecode(merit);
			criteria.createAlias("customer", "cu");
			criteria.add(Restrictions.eq("cu.merit", merit));
		}
		if (ids != null && ids.trim().length() > 0) {
			if (person == null) {
				person = new Person();
				person.setId(Integer.parseInt(ids));
			}
			criteria.add(Restrictions.eq("recorder", person));
		}

		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getCustomerService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "exportContactCountReport", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "${contentType}", "inputName", "inputStream",
			"bufferSize", "1024", "contentDisposition",
			"filename=${outfileName}" }) })
	public String exportContactCountReport() {
		ReportTable table = new ReportTable("导出跟进报表");
		table.addCell(new ReportCell("编号", "id"));
		table.addCell(new ReportCell("客户", "customer.name"));
		table.addCell(new ReportCell("行业", "customer.trade.name"));
		table.addCell(new ReportCell("客户级别", "customer.level.name"));
		table.addCell(new ReportCell("客户价值", "customer.merit"));
		table.addCell(new ReportCell("联络时间", "liaisonTime"));
		table.addCell(new ReportCell("下次联络", "nextLiaison"));
		table.addCell(new ReportCell("联络人", "recorder.resume.name"));
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Liaison.class);
		criteria.add(Restrictions.ge("liaisonTime", beginTime));
		criteria.add(Restrictions.lt("liaisonTime", endTime));
		if (person != null)
			criteria.add(Restrictions.eq("recorder", person));
		if (merit != null && merit.trim().length() > 0) {
			criteria.createAlias("customer", "cu");
			criteria.add(Restrictions.eq("cu.merit", merit));
		}
		this.setOutFilePath(this.getReportService().report(criteria, table,
				new ExportConfig(), this.getExportType()));
		return SUCCESS;
	}

	@Action("contactReport")
	public String contactReport() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Linkman.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getLinkmanService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "exportContactReport", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "${contentType}", "inputName", "inputStream",
			"bufferSize", "1024", "contentDisposition",
			"filename=${outfileName}" }) })
	public String exportContactReport() {

		ReportTable table = new ReportTable("联系人报表");
		table.addCell(new ReportCell("联系人编号", "id"));
		table.addCell(new ReportCell("姓名", "name"));
		table.addCell(new ReportCell("客户", "customer.name"));
		table.addCell(new ReportCell("部门", "dept"));
		table.addCell(new ReportCell("职位", "role"));
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Linkman.class);
		
		this.setOutFilePath(this.getReportService().report(criteria, table,
				new ExportConfig(), this.getExportType()));
		return SUCCESS;
	}

	public Linkman getLinkman() {
		return linkman;
	}

	public LinkmanService getLinkmanService() {
		return linkmanService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setLinkman(Linkman linkman) {
		this.linkman = linkman;
	}

	public void setLinkmanService(LinkmanService linkmanService) {
		this.linkmanService = linkmanService;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public Date getDatestart() {
		return datestart;
	}

	public Date getDateend() {
		return dateend;
	}

	public void setDatestart(Date datestart) {
		this.datestart = datestart;
	}

	public void setDateend(Date dateend) {
		this.dateend = dateend;
	}

	public ChartService getChartService() {
		return chartService;
	}

	public void setChartService(ChartService chartService) {
		this.chartService = chartService;
	}

	public ChartResult getChartResult() {
		return chartResult;
	}

	public void setChartResult(ChartResult chartResult) {
		this.chartResult = chartResult;
	}

	public int getExportType() {
		return exportType;
	}

	public void setExportType(int exportType) {
		this.exportType = exportType;
	}

	public Integer getState() {
		return state;
	}

	public String getYear() {
		return year;
	}

	public String getMonth() {
		return month;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public String getLeaveName() {
		return leaveName;
	}

	public void setLeaveName(String leaveName) {
		this.leaveName = leaveName;
	}

	public String getMerit() {
		return merit;
	}

	public void setMerit(String merit) {
		this.merit = merit;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public Date getBeginTime() {
		return beginTime;
	}

	public void setBeginTime(Date beginTime) {
		this.beginTime = beginTime;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

}
